/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import persistence.ProductPersistFactory;
import persistence.ProductoDAO;
import model.Producto;

/**
 *
 * @author Alex
 */
public class CreateServlet extends MyCoolServlet {

    @Override
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        ProductoDAO persistenceManager = ProductPersistFactory.getProductDAO(persistenceMechanism);
        Producto product = generateProductFromRequest(request);
        
        if (product != null && persistenceManager.newProduct(product)) {
            request.setAttribute("product", product);
            request.setAttribute("message", "ha sido creado con éxito");
            gotoURL(successForm, request, response);
        } else {
            gotoURL(errorForm, request, response);
        }
    }

    Producto generateProductFromRequest(HttpServletRequest request) throws NumberFormatException {
        Producto product = new Producto();
        String name = request.getParameter("nombre");
        String desCorta = request.getParameter("descorta");
        String desLarga = request.getParameter("deslarga");
        String stock = request.getParameter("stock");
        String precio = request.getParameter("precio");

        if (true) {

            //validaciones
        }
        int stockBien = Integer.parseInt(stock);
        double precioBien = Double.parseDouble(precio);
        product.setNombre(name);
        product.setDesCorta(desCorta);
        product.setDesLarga(desLarga);
        product.setPrecio(precioBien);
        product.setStock(stockBien);
        return product;
    }

    private boolean valiateName(String name) {
        String namePattern = "[A-Z]([a-zA-Z������������ ])*";
        return name.matches(namePattern);
    }

    private boolean valiatePhone(String phone) {
        boolean isGoodLength = checkLength(phone, 9, 15);
        return phone.matches("([0-9  +])*") && isGoodLength;
    }

    private boolean valiateAge(String age) {
        boolean isGoodLength = checkLength(age, 1, 3);
        if (age.matches("([0-9])*") && isGoodLength) {
            int ageInt = Integer.valueOf(age);
            return ageInt < 120;
        }
        return false;
    }


    private boolean checkLength(String data, int minAceptable, int maxAceptable) {
        int length = data.length();
        boolean isGoodLength = length >= minAceptable && length <= maxAceptable;
        return isGoodLength;
    }
}
